package com.wkn.wknAdmin.service.impl;

import com.wkn.wknAdmin.entity.Menu;
import com.wkn.wknAdmin.entity.Role;
import com.wkn.wknAdmin.mapper.MenuMapper;
import com.wkn.wknAdmin.mapper.RoleMapper;
import com.wkn.wknAdmin.result.ResultVO;
import com.wkn.wknAdmin.service.MenuService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title:
 * @Description:
 * @Author: WKN
 * CreateDate: 2022/8/13 14:34
 */
@Service
public class MenuServiceImpl implements MenuService {


    ResultVO result = new ResultVO();


    @Resource
    private MenuMapper menuMapper;

    @Override
    public ResultVO save(Menu menu) {
        String name = menu.getMname();
        Menu getMenu = menuMapper.getOne(name);
        if (menu.getId() == null) {
            if (getMenu != null) {
                return result.Fail("菜单名已存在");
            }
            int insert = menuMapper.insert(menu);
            return insert > 0 ? result.Success("添加成功") : result.Fail("添加失败");
        }
        int update = menuMapper.update(menu);
        return update > 0 ? result.Success("修改成功") : result.Fail("修改失败");
    }



    @Override
    public Menu getOne(String mname) {
        return menuMapper.getOne(mname);
    }




    @Override
    public ResultVO findAll() {
        List<Menu> menus = menuMapper.findAll();
        // pid 为null的一级菜单
        List<Menu> pMenus = menus.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList());

        // 找出一级菜单的子菜单
        for(Menu menu : pMenus){
            menu.setChildren(menus.stream().filter(m -> menu.getId().equals(m.getPid())).collect(Collectors.toList()));
        }
        return result.Success(pMenus);
    }


    @Override
    public List<Menu> findMenuByIds(List<Integer> ids) {
        return menuMapper.findMenuByIds(ids);
    }


    @Override
    public List<Integer> findAllIds() {
        return menuMapper.findAllIds();
    }
}
